<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>java8函数式编程 | 牛牛&amp;blog</title><meta name="author" content="牛牛"><meta name="copyright" content="牛牛"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="函数式编程-Stream流1. 概述1.1 为什么学？ 能够看懂公司里的代码 大数量下处理集合效率高 代码可读性高 消灭嵌套地狱  &#x2F;&#x2F;查询未成年作家的评分在70以上的书籍 由于洋流影响所以作家和书籍可能出现重复，需要进行去重List&lt;Book&gt; bookList &#x3D; new ArrayList&lt;&gt;();Set&lt;Book&gt; uniqueBookValues &#x3D;">
<meta property="og:type" content="article">
<meta property="og:title" content="java8函数式编程">
<meta property="og:url" content="https://code-ran.gitee.io/2022/11/23/java8%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/index.html">
<meta property="og:site_name" content="牛牛&amp;blog">
<meta property="og:description" content="函数式编程-Stream流1. 概述1.1 为什么学？ 能够看懂公司里的代码 大数量下处理集合效率高 代码可读性高 消灭嵌套地狱  &#x2F;&#x2F;查询未成年作家的评分在70以上的书籍 由于洋流影响所以作家和书籍可能出现重复，需要进行去重List&lt;Book&gt; bookList &#x3D; new ArrayList&lt;&gt;();Set&lt;Book&gt; uniqueBookValues &#x3D;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="">
<meta property="article:published_time" content="2022-11-23T07:28:14.000Z">
<meta property="article:modified_time" content="2023-11-02T03:32:07.129Z">
<meta property="article:author" content="牛牛">
<meta property="article:tag" content="java8">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content=""><link rel="shortcut icon" href="/img/myfavicon.png"><link rel="canonical" href="https://code-ran.gitee.io/2022/11/23/java8%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'java8函数式编程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-11-02 11:32:07'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/style.css"><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/ys.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">52</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">26</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">26</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">牛牛&amp;blog</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">java8函数式编程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-11-23T07:28:14.000Z" title="发表于 2022-11-23 15:28:14">2022-11-23</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-11-02T03:32:07.129Z" title="更新于 2023-11-02 11:32:07">2023-11-02</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/java8%E7%9B%B8%E5%85%B3/">java8相关</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="java8函数式编程"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="函数式编程-Stream流"><a href="#函数式编程-Stream流" class="headerlink" title="函数式编程-Stream流"></a>函数式编程-Stream流</h1><h2 id="1-概述"><a href="#1-概述" class="headerlink" title="1. 概述"></a>1. 概述</h2><h3 id="1-1-为什么学？"><a href="#1-1-为什么学？" class="headerlink" title="1.1 为什么学？"></a>1.1 为什么学？</h3><ul>
<li>能够看懂公司里的代码</li>
<li>大数量下处理集合效率高</li>
<li>代码可读性高</li>
<li>消灭嵌套地狱</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//查询未成年作家的评分在70以上的书籍 由于洋流影响所以作家和书籍可能出现重复，需要进行去重</span></span><br><span class="line">List&lt;Book&gt; bookList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">Set&lt;Book&gt; uniqueBookValues = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line">Set&lt;Author&gt; uniqueAuthorValues = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line"><span class="keyword">for</span> (Author author : authors) &#123;</span><br><span class="line">    <span class="keyword">if</span> (uniqueAuthorValues.add(author)) &#123;</span><br><span class="line">        <span class="keyword">if</span> (author.getAge() &lt; <span class="number">18</span>) &#123;</span><br><span class="line">            List&lt;Book&gt; books = author.getBooks();</span><br><span class="line">            <span class="keyword">for</span> (Book book : books) &#123;</span><br><span class="line">                <span class="keyword">if</span> (book.getScore() &gt; <span class="number">70</span>) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (uniqueBookValues.add(book)) &#123;</span><br><span class="line">                        bookList.add(book);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">System.out.println(bookList);</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Book&gt; collect = authors.stream()</span><br><span class="line">    .distinct()</span><br><span class="line">    .filter(author -&gt; author.getAge() &lt; <span class="number">18</span>)</span><br><span class="line">    .map(author -&gt; author.getBooks())</span><br><span class="line">    .flatMap(Collection::stream)</span><br><span class="line">    .filter(book -&gt; book.getScore() &gt; <span class="number">70</span>)</span><br><span class="line">    .distinct()</span><br><span class="line">    .collect(Collectors.toList());</span><br><span class="line">System.out.println(collect);</span><br></pre></td></tr></table></figure>



<h3 id="1-2-函数式编程思想"><a href="#1-2-函数式编程思想" class="headerlink" title="1.2 函数式编程思想"></a>1.2 函数式编程思想</h3><h4 id="1-2-1-概念"><a href="#1-2-1-概念" class="headerlink" title="1.2.1 概念"></a>1.2.1 概念</h4><p>​    面向对象思想需要关注用什么对象完成什么事情。而函数式编程思想就类似于我们数学中的函数。它主要关注的是对数据进行了什么操作。</p>
<h4 id="1-2-2-优点"><a href="#1-2-2-优点" class="headerlink" title="1.2.2 优点"></a>1.2.2 优点</h4><ul>
<li>代码简洁，开发快速</li>
<li>接近自然语言，易于理解</li>
<li>易于”并发编程”</li>
</ul>
<h2 id="2-Lambda表达式"><a href="#2-Lambda表达式" class="headerlink" title="2. Lambda表达式"></a>2. Lambda表达式</h2><h3 id="2-1-概述"><a href="#2-1-概述" class="headerlink" title="2.1 概述"></a>2.1 概述</h3><p>​    Lambda是JDK8中一个语法糖。他可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象。而是更关注我们对数据进行了什么操作。</p>
<h3 id="2-2-核心原则"><a href="#2-2-核心原则" class="headerlink" title="2.2 核心原则"></a>2.2 核心原则</h3><blockquote>
<p>可推导可省略</p>
</blockquote>
<h3 id="2-3-基本格式"><a href="#2-3-基本格式" class="headerlink" title="2. 3 基本格式"></a>2. 3 基本格式</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">(参数列表)-&gt;&#123;代码&#125;</span><br></pre></td></tr></table></figure>

<h4 id="例一"><a href="#例一" class="headerlink" title="例一"></a>例一</h4><p>我们在创建线程并启动时可以使用匿名内部类的写法：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;你知道吗 我比你想象的 更想在你身边&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;).start();</span><br></pre></td></tr></table></figure>

<p>可以使用Lambda的格式对其进行修改。修改后如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> Thread(()-&gt;&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;你知道吗 我比你想象的 更想在你身边&quot;</span>);</span><br><span class="line">&#125;).start();</span><br></pre></td></tr></table></figure>



<h4 id="例二"><a href="#例二" class="headerlink" title="例二:"></a>例二:</h4><p>现有方法定义如下，其中IntBinaryOperator是一个接口。先使用匿名内部类的写法调用该方法。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">calculateNum</span><span class="params">(IntBinaryOperator operator)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a = <span class="number">10</span>;</span><br><span class="line">    <span class="keyword">int</span> b = <span class="number">20</span>;</span><br><span class="line">    <span class="keyword">return</span> operator.applyAsInt(a, b);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i = calculateNum(<span class="keyword">new</span> IntBinaryOperator() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">applyAsInt</span><span class="params">(<span class="keyword">int</span> left, <span class="keyword">int</span> right)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> left + right;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    System.out.println(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Lambda写法：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i = calculateNum((<span class="keyword">int</span> left, <span class="keyword">int</span> right)-&gt;&#123;</span><br><span class="line">        <span class="keyword">return</span> left + right;</span><br><span class="line">    &#125;);</span><br><span class="line">    System.out.println(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="例三："><a href="#例三：" class="headerlink" title="例三："></a>例三：</h4><p>现有方法定义如下，其中IntPredicate是一个接口。先使用匿名内部类的写法调用该方法。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printNum</span><span class="params">(IntPredicate predicate)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>[] arr = &#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>&#125;;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i : arr) &#123;</span><br><span class="line">        <span class="keyword">if</span>(predicate.test(i))&#123;</span><br><span class="line">            System.out.println(i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    printNum(<span class="keyword">new</span> IntPredicate() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">test</span><span class="params">(<span class="keyword">int</span> value)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> value%<span class="number">2</span>==<span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Lambda写法：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    printNum((<span class="keyword">int</span> value)-&gt; &#123;</span><br><span class="line">        <span class="keyword">return</span> value%<span class="number">2</span>==<span class="number">0</span>;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printNum</span><span class="params">(IntPredicate predicate)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>[] arr = &#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>&#125;;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i : arr) &#123;</span><br><span class="line">        <span class="keyword">if</span>(predicate.test(i))&#123;</span><br><span class="line">            System.out.println(i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="例四："><a href="#例四：" class="headerlink" title="例四："></a>例四：</h4><p>现有方法定义如下，其中Function是一个接口。先使用匿名内部类的写法调用该方法。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;R&gt; <span class="function">R <span class="title">typeConver</span><span class="params">(Function&lt;String,R&gt; function)</span></span>&#123;</span><br><span class="line">    String str = <span class="string">&quot;1235&quot;</span>;</span><br><span class="line">    R result = function.apply(str);</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    Integer result = typeConver(<span class="keyword">new</span> Function&lt;String, Integer&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Integer <span class="title">apply</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> Integer.valueOf(s);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    System.out.println(result);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Lambda写法：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Integer result = typeConver((String s)-&gt;&#123;</span><br><span class="line">    <span class="keyword">return</span> Integer.valueOf(s);</span><br><span class="line">&#125;);</span><br><span class="line">System.out.println(result);</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h4 id="例五："><a href="#例五：" class="headerlink" title="例五："></a>例五：</h4><p>现有方法定义如下，其中IntConsumer是一个接口。先使用匿名内部类的写法调用该方法。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">foreachArr</span><span class="params">(IntConsumer consumer)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>[] arr = &#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>&#125;;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i : arr) &#123;</span><br><span class="line">        consumer.accept(i);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    foreachArr(<span class="keyword">new</span> IntConsumer() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">accept</span><span class="params">(<span class="keyword">int</span> value)</span> </span>&#123;</span><br><span class="line">            System.out.println(value);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Lambda写法：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    foreachArr((<span class="keyword">int</span> value)-&gt;&#123;</span><br><span class="line">        System.out.println(value);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="2-4-省略规则"><a href="#2-4-省略规则" class="headerlink" title="2.4 省略规则"></a>2.4 省略规则</h3><ul>
<li>参数类型可以省略</li>
<li>方法体只有一句代码时大括号return和唯一一句代码的分号可以省略</li>
<li>方法只有一个参数时小括号可以省略</li>
<li>以上这些规则都记不住也可以省略不记</li>
</ul>
<h2 id="3-Stream流"><a href="#3-Stream流" class="headerlink" title="3. Stream流"></a>3. Stream流</h2><h3 id="3-1-概述"><a href="#3-1-概述" class="headerlink" title="3.1 概述"></a>3.1 概述</h3><p>​    Java8的Stream使用的是函数式编程模式，如同它的名字一样，它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作。</p>
<h3 id="3-2-案例数据准备"><a href="#3-2-案例数据准备" class="headerlink" title="3.2 案例数据准备"></a>3.2 案例数据准备</h3><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.18.16<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@EqualsAndHashCode</span><span class="comment">//用于后期的去重使用</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Author</span> </span>&#123;</span><br><span class="line">    <span class="comment">//id</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="comment">//姓名</span></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="comment">//年龄</span></span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line">    <span class="comment">//简介</span></span><br><span class="line">    <span class="keyword">private</span> String intro;</span><br><span class="line">    <span class="comment">//作品</span></span><br><span class="line">    <span class="keyword">private</span> List&lt;Book&gt; books;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@EqualsAndHashCode</span><span class="comment">//用于后期的去重使用</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Book</span> </span>&#123;</span><br><span class="line">    <span class="comment">//id</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="comment">//书名</span></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//分类</span></span><br><span class="line">    <span class="keyword">private</span> String category;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//评分</span></span><br><span class="line">    <span class="keyword">private</span> Integer score;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//简介</span></span><br><span class="line">    <span class="keyword">private</span> String intro;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> List&lt;Author&gt; <span class="title">getAuthors</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//数据初始化</span></span><br><span class="line">    Author author = <span class="keyword">new</span> Author(<span class="number">1L</span>,<span class="string">&quot;蒙多&quot;</span>,<span class="number">33</span>,<span class="string">&quot;一个从菜刀中明悟哲理的祖安人&quot;</span>,<span class="keyword">null</span>);</span><br><span class="line">    Author author2 = <span class="keyword">new</span> Author(<span class="number">2L</span>,<span class="string">&quot;亚拉索&quot;</span>,<span class="number">15</span>,<span class="string">&quot;狂风也追逐不上他的思考速度&quot;</span>,<span class="keyword">null</span>);</span><br><span class="line">    Author author3 = <span class="keyword">new</span> Author(<span class="number">3L</span>,<span class="string">&quot;易&quot;</span>,<span class="number">14</span>,<span class="string">&quot;是这个世界在限制他的思维&quot;</span>,<span class="keyword">null</span>);</span><br><span class="line">    Author author4 = <span class="keyword">new</span> Author(<span class="number">3L</span>,<span class="string">&quot;易&quot;</span>,<span class="number">14</span>,<span class="string">&quot;是这个世界在限制他的思维&quot;</span>,<span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//书籍列表</span></span><br><span class="line">    List&lt;Book&gt; books1 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    List&lt;Book&gt; books2 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    List&lt;Book&gt; books3 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    books1.add(<span class="keyword">new</span> Book(<span class="number">1L</span>,<span class="string">&quot;刀的两侧是光明与黑暗&quot;</span>,<span class="string">&quot;哲学,爱情&quot;</span>,<span class="number">88</span>,<span class="string">&quot;用一把刀划分了爱恨&quot;</span>));</span><br><span class="line">    books1.add(<span class="keyword">new</span> Book(<span class="number">2L</span>,<span class="string">&quot;一个人不能死在同一把刀下&quot;</span>,<span class="string">&quot;个人成长,爱情&quot;</span>,<span class="number">99</span>,<span class="string">&quot;讲述如何从失败中明悟真理&quot;</span>));</span><br><span class="line"></span><br><span class="line">    books2.add(<span class="keyword">new</span> Book(<span class="number">3L</span>,<span class="string">&quot;那风吹不到的地方&quot;</span>,<span class="string">&quot;哲学&quot;</span>,<span class="number">85</span>,<span class="string">&quot;带你用思维去领略世界的尽头&quot;</span>));</span><br><span class="line">    books2.add(<span class="keyword">new</span> Book(<span class="number">3L</span>,<span class="string">&quot;那风吹不到的地方&quot;</span>,<span class="string">&quot;哲学&quot;</span>,<span class="number">85</span>,<span class="string">&quot;带你用思维去领略世界的尽头&quot;</span>));</span><br><span class="line">    books2.add(<span class="keyword">new</span> Book(<span class="number">4L</span>,<span class="string">&quot;吹或不吹&quot;</span>,<span class="string">&quot;爱情,个人传记&quot;</span>,<span class="number">56</span>,<span class="string">&quot;一个哲学家的恋爱观注定很难把他所在的时代理解&quot;</span>));</span><br><span class="line"></span><br><span class="line">    books3.add(<span class="keyword">new</span> Book(<span class="number">5L</span>,<span class="string">&quot;你的剑就是我的剑&quot;</span>,<span class="string">&quot;爱情&quot;</span>,<span class="number">56</span>,<span class="string">&quot;无法想象一个武者能对他的伴侣这么的宽容&quot;</span>));</span><br><span class="line">    books3.add(<span class="keyword">new</span> Book(<span class="number">6L</span>,<span class="string">&quot;风与剑&quot;</span>,<span class="string">&quot;个人传记&quot;</span>,<span class="number">100</span>,<span class="string">&quot;两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢？&quot;</span>));</span><br><span class="line">    books3.add(<span class="keyword">new</span> Book(<span class="number">6L</span>,<span class="string">&quot;风与剑&quot;</span>,<span class="string">&quot;个人传记&quot;</span>,<span class="number">100</span>,<span class="string">&quot;两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢？&quot;</span>));</span><br><span class="line"></span><br><span class="line">    author.setBooks(books1);</span><br><span class="line">    author2.setBooks(books2);</span><br><span class="line">    author3.setBooks(books3);</span><br><span class="line">    author4.setBooks(books3);</span><br><span class="line"></span><br><span class="line">    List&lt;Author&gt; authorList = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(author,author2,author3,author4));</span><br><span class="line">    <span class="keyword">return</span> authorList;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="3-3-快速入门"><a href="#3-3-快速入门" class="headerlink" title="3.3 快速入门"></a>3.3 快速入门</h3><h4 id="3-3-1-需求"><a href="#3-3-1-需求" class="headerlink" title="3.3.1 需求"></a>3.3.1 需求</h4><p>​    我们可以调用getAuthors方法获取到作家的集合。现在需要打印所有年龄小于18的作家的名字，并且要注意去重。</p>
<h4 id="3-3-2-实现"><a href="#3-3-2-实现" class="headerlink" title="3.3.2 实现"></a>3.3.2 实现</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//打印所有年龄小于18的作家的名字，并且要注意去重</span></span><br><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">authors.</span><br><span class="line">        stream()<span class="comment">//把集合转换成流</span></span><br><span class="line">        .distinct()<span class="comment">//先去除重复的作家</span></span><br><span class="line">        .filter(author -&gt; author.getAge()&lt;<span class="number">18</span>)<span class="comment">//筛选年龄小于18的</span></span><br><span class="line">        .forEach(author -&gt; System.out.println(author.getName()));<span class="comment">//遍历打印名字</span></span><br></pre></td></tr></table></figure>



<h3 id="3-4-常用操作"><a href="#3-4-常用操作" class="headerlink" title="3.4 常用操作"></a>3.4 常用操作</h3><h4 id="3-4-1-创建流"><a href="#3-4-1-创建流" class="headerlink" title="3.4.1 创建流"></a>3.4.1 创建流</h4><p>单列集合： <code>集合对象.stream()</code></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">      List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">Stream&lt;Author&gt; stream = authors.stream();</span><br></pre></td></tr></table></figure>

<p>数组：<code>Arrays.stream(数组) </code>或者使用<code>Stream.of</code>来创建</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Integer[] arr = &#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>&#125;;</span><br><span class="line">Stream&lt;Integer&gt; stream = Arrays.stream(arr);</span><br><span class="line">Stream&lt;Integer&gt; stream2 = Stream.of(arr);</span><br></pre></td></tr></table></figure>

<p>双列集合：转换成单列集合后再创建</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Map&lt;String,Integer&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">map.put(<span class="string">&quot;蜡笔小新&quot;</span>,<span class="number">19</span>);</span><br><span class="line">map.put(<span class="string">&quot;黑子&quot;</span>,<span class="number">17</span>);</span><br><span class="line">map.put(<span class="string">&quot;日向翔阳&quot;</span>,<span class="number">16</span>);</span><br><span class="line"></span><br><span class="line">Stream&lt;Map.Entry&lt;String, Integer&gt;&gt; stream = map.entrySet().stream();</span><br></pre></td></tr></table></figure>



<h4 id="3-4-2-中间操作"><a href="#3-4-2-中间操作" class="headerlink" title="3.4.2 中间操作"></a>3.4.2 中间操作</h4><h5 id="filter"><a href="#filter" class="headerlink" title="filter"></a>filter</h5><p>​    可以对流中的元素进行条件过滤，符合过滤条件的才能继续留在流中。</p>
<p>例如：</p>
<p>​    打印所有姓名长度大于1的作家的姓名</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">authors.stream()</span><br><span class="line">        .filter(author -&gt; author.getName().length()&gt;<span class="number">1</span>)</span><br><span class="line">        .forEach(author -&gt; System.out.println(author.getName()));</span><br></pre></td></tr></table></figure>



<h5 id="map"><a href="#map" class="headerlink" title="map"></a>map</h5><p>​    可以把对流中的元素进行计算或转换。</p>
<p>例如：</p>
<p>​    打印所有作家的姓名</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line">authors</span><br><span class="line">        .stream()</span><br><span class="line">        .map(author -&gt; author.getName())</span><br><span class="line">        .forEach(name-&gt;System.out.println(name));</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        打印所有作家的姓名</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line"><span class="comment">//        authors.stream()</span></span><br><span class="line"><span class="comment">//                .map(author -&gt; author.getName())</span></span><br><span class="line"><span class="comment">//                .forEach(s -&gt; System.out.println(s));</span></span><br><span class="line"></span><br><span class="line">        authors.stream()</span><br><span class="line">                .map(author -&gt; author.getAge())</span><br><span class="line">                .map(age-&gt;age+<span class="number">10</span>)</span><br><span class="line">                .forEach(age-&gt; System.out.println(age));</span><br></pre></td></tr></table></figure>





<h5 id="distinct"><a href="#distinct" class="headerlink" title="distinct"></a>distinct</h5><p>​    可以去除流中的重复元素。</p>
<p>例如：</p>
<p>​    打印所有作家的姓名，并且要求其中不能有重复元素。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">authors.stream()</span><br><span class="line">        .distinct()</span><br><span class="line">        .forEach(author -&gt; System.out.println(author.getName()));</span><br></pre></td></tr></table></figure>



<p><strong>注意：distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重写equals方法。</strong></p>
<h5 id="sorted"><a href="#sorted" class="headerlink" title="sorted"></a>sorted</h5><p>​    可以对流中的元素进行排序。</p>
<p>例如：</p>
<p>​    对流中的元素按照年龄进行降序排序，并且要求不能有重复的元素。</p>
<p>(1)sorted()方法不带参数时：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"><span class="comment">//        对流中的元素按照年龄进行降序排序，并且要求不能有重复的元素。</span></span><br><span class="line">        authors.stream()</span><br><span class="line">                .distinct()</span><br><span class="line">                .sorted()</span><br><span class="line">                .forEach(author -&gt; System.out.println(author.getAge()));</span><br></pre></td></tr></table></figure>

<p>   直接调sorted()方法运行是会报错的，因为没有实现Comparable接口。会报如下错误：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Exception in thread <span class="string">&quot;main&quot;</span> java.lang.ClassCastException: com.ransibi.streampractice.pojo.Author cannot be cast to java.lang.Comparable</span><br><span class="line">	at java.util.Comparators$NaturalOrderComparator.compare(Comparators.java:<span class="number">47</span>)</span><br><span class="line">	at java.util.TimSort.countRunAndMakeAscending(TimSort.java:<span class="number">355</span>)</span><br><span class="line">	at java.util.TimSort.sort(TimSort.java:<span class="number">220</span>)</span><br><span class="line">	at java.util.Arrays.sort(Arrays.java:<span class="number">1512</span>)</span><br><span class="line">	at java.util.ArrayList.sort(ArrayList.java:<span class="number">1464</span>)</span><br><span class="line">	at java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:<span class="number">392</span>)</span><br><span class="line">	at java.util.stream.DistinctOps$<span class="number">1</span>$<span class="number">2.</span>end(DistinctOps.java:<span class="number">168</span>)</span><br><span class="line">	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:<span class="number">483</span>)</span><br><span class="line">	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:<span class="number">472</span>)</span><br><span class="line">	at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:<span class="number">150</span>)</span><br><span class="line">	at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:<span class="number">173</span>)</span><br><span class="line">	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:<span class="number">234</span>)</span><br><span class="line">	at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:<span class="number">485</span>)</span><br><span class="line">	at com.ransibi.streampractice.mediumoperator.Demo.test03(Demo.java:<span class="number">174</span>)</span><br><span class="line">	at com.ransibi.streampractice.mediumoperator.Demo.main(Demo.java:<span class="number">32</span>)</span><br></pre></td></tr></table></figure>

<p>  解决方法：需要在实体中实现Comparable方法：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> com.ransibi.streampractice.pojo;</span><br><span class="line"><span class="keyword">import</span> lombok.AllArgsConstructor;</span><br><span class="line"><span class="keyword">import</span> lombok.Data;</span><br><span class="line"><span class="keyword">import</span> lombok.EqualsAndHashCode;</span><br><span class="line"><span class="keyword">import</span> lombok.NoArgsConstructor;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span> &amp;&#123;NAME&#125;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span> Author</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span> code-ran</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span> 2022/5/16 17:52</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@EqualsAndHashCode</span><span class="comment">//用于去重使用</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Author</span> <span class="keyword">implements</span> <span class="title">Comparable</span>&lt;<span class="title">Author</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Long id;<span class="comment">//id</span></span><br><span class="line">    <span class="keyword">private</span> String name;<span class="comment">//姓名</span></span><br><span class="line">    <span class="keyword">private</span> Integer age;<span class="comment">//年龄</span></span><br><span class="line">    <span class="keyword">private</span> String intro;<span class="comment">//简介</span></span><br><span class="line">    <span class="keyword">private</span> List&lt;Book&gt; books;<span class="comment">//作品</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//实现流中的soretd方法</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compareTo</span><span class="params">(Author o)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//当前的年龄与传入年龄进行比较</span></span><br><span class="line">        <span class="keyword">return</span> o.getAge() - <span class="keyword">this</span>.getAge();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>（2）sorted()方法带参数时：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"><span class="comment">//    对流中的元素按照年龄进行降序排序，并且要求不能有重复的元素。</span></span><br><span class="line">        authors.stream()</span><br><span class="line">                .distinct()</span><br><span class="line">                .sorted((o1, o2) -&gt; o2.getAge()-o1.getAge())</span><br><span class="line">                .forEach(author -&gt; System.out.println(author.getAge()));</span><br></pre></td></tr></table></figure>



<p><strong>注意：如果调用空参的sorted()方法，需要流中的元素是实现了Comparable。</strong></p>
<p>​        </p>
<h5 id="limit"><a href="#limit" class="headerlink" title="limit"></a>limit</h5><p>​    可以设置流的最大长度，超出的部分将被抛弃。</p>
<p>例如：</p>
<p>​    对流中的元素按照年龄进行降序排序，并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">authors.stream()</span><br><span class="line">        .distinct()</span><br><span class="line">        .sorted()</span><br><span class="line">        .limit(<span class="number">2</span>)</span><br><span class="line">        .forEach(author -&gt; System.out.println(author.getName()));</span><br></pre></td></tr></table></figure>



<h5 id="skip"><a href="#skip" class="headerlink" title="skip"></a>skip</h5><p>​    跳过流中的前n个元素，返回剩下的元素</p>
<p>例如：</p>
<p>​    打印除了年龄最大的作家外的其他作家，要求不能有重复元素，并且按照年龄降序排序。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        打印除了年龄最大的作家外的其他作家，要求不能有重复元素，并且按照年龄降序排序。</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        authors.stream()</span><br><span class="line">                .distinct()</span><br><span class="line">                .sorted()</span><br><span class="line">                .skip(<span class="number">1</span>)</span><br><span class="line">                .forEach(author -&gt; System.out.println(author.getName()));</span><br></pre></td></tr></table></figure>







<h5 id="flatMap"><a href="#flatMap" class="headerlink" title="flatMap"></a>flatMap</h5><p>​    map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。</p>
<p>例一：</p>
<p>​    打印所有书籍的名字。要求对重复的元素进行去重。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        打印所有书籍的名字。要求对重复的元素进行去重。</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line">        authors.stream()</span><br><span class="line">                .flatMap(author -&gt; author.getBooks().stream())</span><br><span class="line">                .distinct()</span><br><span class="line">                .forEach(book -&gt; System.out.println(book.getName()));</span><br></pre></td></tr></table></figure>



<p>例二：</p>
<p>​    打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式：哲学,爱情</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式：哲学,爱情     爱情</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        authors.stream()</span><br><span class="line">                .flatMap(author -&gt; author.getBooks().stream())</span><br><span class="line">                .distinct()</span><br><span class="line">                .flatMap(book -&gt; Arrays.stream(book.getCategory().split(<span class="string">&quot;,&quot;</span>)))</span><br><span class="line">                .distinct()</span><br><span class="line">                .forEach(category-&gt; System.out.println(category));</span><br></pre></td></tr></table></figure>





<h4 id="3-4-3-终结操作"><a href="#3-4-3-终结操作" class="headerlink" title="3.4.3 终结操作"></a>3.4.3 终结操作</h4><h5 id="forEach"><a href="#forEach" class="headerlink" title="forEach"></a>forEach</h5><p>​    对流中的元素进行遍历操作，我们通过传入的参数去指定对遍历到的元素进行什么具体操作。</p>
<p>例子：</p>
<p>​    输出所有作家的名字</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        输出所有作家的名字</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line">        authors.stream()</span><br><span class="line">                .map(author -&gt; author.getName())</span><br><span class="line">                .distinct()</span><br><span class="line">                .forEach(name-&gt; System.out.println(name));</span><br><span class="line"></span><br></pre></td></tr></table></figure>





<h5 id="count"><a href="#count" class="headerlink" title="count"></a>count</h5><p>​    可以用来获取当前流中元素的个数。</p>
<p>例子：</p>
<p>​    打印这些作家的所出书籍的数目，注意删除重复元素。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        打印这些作家的所出书籍的数目，注意删除重复元素。</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> count = authors.stream()</span><br><span class="line">                .flatMap(author -&gt; author.getBooks().stream())</span><br><span class="line">                .distinct()</span><br><span class="line">                .count();</span><br><span class="line">        System.out.println(count);</span><br></pre></td></tr></table></figure>





<h5 id="max-amp-min"><a href="#max-amp-min" class="headerlink" title="max&amp;min"></a>max&amp;min</h5><p>​    可以用来或者流中的最值。</p>
<p>例子：</p>
<p>​    分别获取这些作家的所出书籍的最高分和最低分并打印。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        分别获取这些作家的所出书籍的最高分和最低分并打印。</span></span><br><span class="line">        <span class="comment">//Stream&lt;Author&gt;  -&gt; Stream&lt;Book&gt; -&gt;Stream&lt;Integer&gt;  -&gt;求值</span></span><br><span class="line"></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        Optional&lt;Integer&gt; max = authors.stream()</span><br><span class="line">                .flatMap(author -&gt; author.getBooks().stream())</span><br><span class="line">                .map(book -&gt; book.getScore())</span><br><span class="line">                .max((score1, score2) -&gt; score1 - score2);</span><br><span class="line"></span><br><span class="line">        Optional&lt;Integer&gt; min = authors.stream()</span><br><span class="line">                .flatMap(author -&gt; author.getBooks().stream())</span><br><span class="line">                .map(book -&gt; book.getScore())</span><br><span class="line">                .min((score1, score2) -&gt; score1 - score2);</span><br><span class="line">        System.out.println(max.get());</span><br><span class="line">        System.out.println(min.get());</span><br></pre></td></tr></table></figure>







<h5 id="collect"><a href="#collect" class="headerlink" title="collect"></a>collect</h5><p>​    把当前流转换成一个集合。</p>
<p>例子：</p>
<p>​    获取一个存放所有作者名字的List集合。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        获取一个存放所有作者名字的List集合。</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        List&lt;String&gt; nameList = authors.stream()</span><br><span class="line">                .map(author -&gt; author.getName())</span><br><span class="line">                .collect(Collectors.toList());</span><br><span class="line">        System.out.println(nameList);</span><br></pre></td></tr></table></figure>

<p>​    获取一个所有书名的Set集合。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        获取一个所有书名的Set集合。</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        Set&lt;Book&gt; books = authors.stream()</span><br><span class="line">                .flatMap(author -&gt; author.getBooks().stream())</span><br><span class="line">                .collect(Collectors.toSet());</span><br><span class="line"></span><br><span class="line">        System.out.println(books);</span><br></pre></td></tr></table></figure>

<p>​    获取一个Map集合，map的key为作者名，value为List<Book></Book></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        获取一个Map集合，map的key为作者名，value为List&lt;Book&gt;</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line">        Map&lt;String, List&lt;Book&gt;&gt; map = authors.stream()</span><br><span class="line">                .distinct()</span><br><span class="line">                .collect(Collectors.toMap(author -&gt; author.getName(), author -&gt; author.getBooks()));</span><br><span class="line"></span><br><span class="line">        System.out.println(map);</span><br></pre></td></tr></table></figure>



<h5 id="查找与匹配"><a href="#查找与匹配" class="headerlink" title="查找与匹配"></a>查找与匹配</h5><h6 id="anyMatch"><a href="#anyMatch" class="headerlink" title="anyMatch"></a>anyMatch</h6><p>​    可以用来判断是否有任意符合匹配条件的元素，结果为boolean类型。</p>
<p>例子：</p>
<p>​    判断是否有年龄在29以上的作家</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        判断是否有年龄在29以上的作家</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        <span class="keyword">boolean</span> flag = authors.stream()</span><br><span class="line">                .anyMatch(author -&gt; author.getAge() &gt; <span class="number">29</span>);</span><br><span class="line">        System.out.println(flag);</span><br></pre></td></tr></table></figure>





<h6 id="allMatch"><a href="#allMatch" class="headerlink" title="allMatch"></a>allMatch</h6><p>​    可以用来判断是否都符合匹配条件，结果为boolean类型。如果都符合结果为true，否则结果为false。</p>
<p>例子：</p>
<p>​    判断是否所有的作家都是成年人</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        判断是否所有的作家都是成年人</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        <span class="keyword">boolean</span> flag = authors.stream()</span><br><span class="line">                .allMatch(author -&gt; author.getAge() &gt;= <span class="number">18</span>);</span><br><span class="line">        System.out.println(flag);</span><br></pre></td></tr></table></figure>



<h6 id="noneMatch"><a href="#noneMatch" class="headerlink" title="noneMatch"></a>noneMatch</h6><p>​    可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true，否则结果为false</p>
<p>例子：</p>
<p>​    判断作家是否都没有超过100岁的。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        判断作家是否都没有超过100岁的。</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">boolean</span> b = authors.stream()</span><br><span class="line">                .noneMatch(author -&gt; author.getAge() &gt; <span class="number">100</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(b);</span><br></pre></td></tr></table></figure>





<h6 id="findAny"><a href="#findAny" class="headerlink" title="findAny"></a>findAny</h6><p>​    获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。</p>
<p>例子：</p>
<p>​    获取任意一个年龄大于18的作家，如果存在就输出他的名字</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        获取任意一个年龄大于18的作家，如果存在就输出他的名字</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        Optional&lt;Author&gt; optionalAuthor = authors.stream()</span><br><span class="line">                .filter(author -&gt; author.getAge()&gt;<span class="number">18</span>)</span><br><span class="line">                .findAny();</span><br><span class="line"></span><br><span class="line">        optionalAuthor.ifPresent(author -&gt; System.out.println(author.getName()));</span><br></pre></td></tr></table></figure>



<h6 id="findFirst"><a href="#findFirst" class="headerlink" title="findFirst"></a>findFirst</h6><p>​    获取流中的第一个元素。</p>
<p>例子：</p>
<p>​    获取一个年龄最小的作家，并输出他的姓名。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        获取一个年龄最小的作家，并输出他的姓名。</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        Optional&lt;Author&gt; first = authors.stream()</span><br><span class="line">                .sorted((o1, o2) -&gt; o1.getAge() - o2.getAge())</span><br><span class="line">                .findFirst();</span><br><span class="line"></span><br><span class="line">        first.ifPresent(author -&gt; System.out.println(author.getName()));</span><br></pre></td></tr></table></figure>



<h5 id="reduce归并"><a href="#reduce归并" class="headerlink" title="reduce归并"></a>reduce归并</h5><p>​    对流中的数据按照你指定的计算方式计算出一个结果。（缩减操作）</p>
<p>​    reduce的作用是把stream中的元素给组合起来，我们可以传入一个初始值，它会按照我们的计算方式依次拿流中的元素和初始化值进行计算，计算结果再和后面的元素计算。</p>
<p>​    reduce两个参数的重载形式内部的计算方式如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">T result = identity;</span><br><span class="line"><span class="keyword">for</span> (T element : <span class="keyword">this</span> stream)</span><br><span class="line">	result = accumulator.apply(result, element)</span><br><span class="line"><span class="keyword">return</span> result;</span><br></pre></td></tr></table></figure>

<p>​    其中identity就是我们可以通过方法参数传入的初始值，accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。</p>
<p>例子：</p>
<p>​    使用reduce求所有作者年龄的和</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        使用reduce求所有作者年龄的和</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        Integer sum = authors.stream()</span><br><span class="line">                .distinct()</span><br><span class="line">                .map(author -&gt; author.getAge())</span><br><span class="line">                .reduce(<span class="number">0</span>, (result, element) -&gt; result + element);</span><br><span class="line">        System.out.println(sum);</span><br></pre></td></tr></table></figure>

<p>​    使用reduce求所有作者中年龄的最大值</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        使用reduce求所有作者中年龄的最大值</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        Integer max = authors.stream()</span><br><span class="line">                .map(author -&gt; author.getAge())</span><br><span class="line">                .reduce(Integer.MIN_VALUE, (result, element) -&gt; result &lt; element ? element : result);</span><br><span class="line"></span><br><span class="line">        System.out.println(max);</span><br></pre></td></tr></table></figure>

<p>​    使用reduce求所有作者中年龄的最小值</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        使用reduce求所有作者中年龄的最小值</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        Integer min = authors.stream()</span><br><span class="line">                .map(author -&gt; author.getAge())</span><br><span class="line">                .reduce(Integer.MAX_VALUE, (result, element) -&gt; result &gt; element ? element : result);</span><br><span class="line">        System.out.println(min);</span><br></pre></td></tr></table></figure>



<p>​    reduce一个参数的重载形式内部的计算</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">boolean</span> foundAny = <span class="keyword">false</span>;</span><br><span class="line">  T result = <span class="keyword">null</span>;</span><br><span class="line">  <span class="keyword">for</span> (T element : <span class="keyword">this</span> stream) &#123;</span><br><span class="line">      <span class="keyword">if</span> (!foundAny) &#123;</span><br><span class="line">          foundAny = <span class="keyword">true</span>;</span><br><span class="line">          result = element;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span></span><br><span class="line">          result = accumulator.apply(result, element);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> foundAny ? Optional.of(result) : Optional.empty();</span><br></pre></td></tr></table></figure>

<p>​    如果用一个参数的重载方法去求最小值代码如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        使用reduce求所有作者中年龄的最小值</span></span><br><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">Optional&lt;Integer&gt; minOptional = authors.stream()</span><br><span class="line">        .map(author -&gt; author.getAge())</span><br><span class="line">        .reduce((result, element) -&gt; result &gt; element ? element : result);</span><br><span class="line">minOptional.ifPresent(age-&gt; System.out.println(age));</span><br></pre></td></tr></table></figure>







<h3 id="3-5-注意事项"><a href="#3-5-注意事项" class="headerlink" title="3.5 注意事项"></a>3.5 注意事项</h3><ul>
<li>惰性求值（如果没有终结操作，没有中间操作是不会得到执行的）</li>
<li>流是一次性的（一旦一个流对象经过一个终结操作后。这个流就不能再被使用）</li>
<li>不会影响原数据（我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的）</li>
</ul>
<h2 id="4-Optional"><a href="#4-Optional" class="headerlink" title="4. Optional"></a>4. Optional</h2><h3 id="4-1-概述"><a href="#4-1-概述" class="headerlink" title="4.1 概述"></a>4.1 概述</h3><p>​    我们在编写代码的时候出现最多的就是空指针异常。所以在很多情况下我们需要做各种非空的判断。</p>
<p>​    例如：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Author author = getAuthor();</span><br><span class="line"><span class="keyword">if</span>(author!=<span class="keyword">null</span>)&#123;</span><br><span class="line">    System.out.println(author.getName());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    尤其是对象中的属性还是一个对象的情况下。这种判断会更多。    </p>
<p>​    而过多的判断语句会让我们的代码显得臃肿不堪。</p>
<p>​    所以在JDK8中引入了Optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免空指针异常。</p>
<p>​    并且在很多函数式编程相关的API中也都用到了Optional，如果不会使用Optional也会对函数式编程的学习造成影响。</p>
<h3 id="4-2-使用"><a href="#4-2-使用" class="headerlink" title="4.2 使用"></a>4.2 使用</h3><h4 id="4-2-1-创建对象"><a href="#4-2-1-创建对象" class="headerlink" title="4.2.1 创建对象"></a>4.2.1 创建对象</h4><p>​    Optional就好像是包装类，可以把我们的具体数据封装Optional对象内部。然后我们去使用Optional中封装好的方法操作封装进去的数据就可以非常优雅的避免空指针异常。</p>
<p>​    我们一般使用<strong>Optional</strong>的<strong>静态方法ofNullable</strong>来把数据封装成一个Optional对象。无论传入的参数是否为null都不会出现问题。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Author author = getAuthor();</span><br><span class="line">Optional&lt;Author&gt; authorOptional = Optional.ofNullable(author);</span><br></pre></td></tr></table></figure>

<p>​    你可能会觉得还要加一行代码来封装数据比较麻烦。但是如果改造下getAuthor方法，让其的返回值就是封装好的Optional的话，我们在使用时就会方便很多。</p>
<p>​    而且在实际开发中我们的数据很多是从数据库获取的。Mybatis从3.5版本可以也已经支持Optional了。我们可以直接把dao方法的返回值类型定义成Optional类型，MyBastis会自己把数据封装成Optional对象返回。封装的过程也不需要我们自己操作。</p>
<p>​    如果你<strong>确定一个对象不是空</strong>的则可以使用<strong>Optional</strong>的<strong>静态方法of</strong>来把数据封装成Optional对象。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Author author = <span class="keyword">new</span> Author();</span><br><span class="line">Optional&lt;Author&gt; authorOptional = Optional.of(author);</span><br></pre></td></tr></table></figure>

<p>​    但是一定要注意，如果使用of的时候传入的参数必须不为null。（尝试下传入null会出现什么结果）</p>
<p>​    如果一个方法的返回值类型是Optional类型。而如果我们经判断发现某次计算得到的返回值为null，这个时候就需要把null封装成Optional对象返回。这时则可以使用<strong>Optional</strong>的<strong>静态方法empty</strong>来进行封装。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Optional.empty()</span><br></pre></td></tr></table></figure>

<p>​    </p>
<p>​    所以最后你觉得哪种方式会更方便呢？<strong>ofNullable</strong></p>
<h4 id="4-2-2-安全消费值"><a href="#4-2-2-安全消费值" class="headerlink" title="4.2.2 安全消费值"></a>4.2.2 安全消费值</h4><p>​    我们获取到一个Optional对象后肯定需要对其中的数据进行使用。这时候我们可以使用其<strong>ifPresent</strong>方法对来消费其中的值。</p>
<p>​    这个方法会判断其内封装的数据是否为空，不为空时才会执行具体的消费代码。这样使用起来就更加安全了。</p>
<p>​    例如,以下写法就优雅的避免了空指针异常。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Optional&lt;Author&gt; authorOptional = Optional.ofNullable(getAuthor());</span><br><span class="line"></span><br><span class="line">authorOptional.ifPresent(author -&gt; System.out.println(author.getName()));</span><br></pre></td></tr></table></figure>



<h4 id="4-2-3-获取值"><a href="#4-2-3-获取值" class="headerlink" title="4.2.3 获取值"></a>4.2.3 获取值</h4><p>​    如果我们想获取值自己进行处理可以使用get方法获取，但是不推荐。因为当Optional内部的数据为空的时候会出现异常。</p>
<h4 id="4-2-4-安全获取值"><a href="#4-2-4-安全获取值" class="headerlink" title="4.2.4 安全获取值"></a>4.2.4 安全获取值</h4><p>​    如果我们期望安全的获取值。我们不推荐使用get方法，而是使用Optional提供的以下方法。</p>
<ul>
<li><p>orElseGet</p>
<p>获取数据并且设置数据为空时的默认值。如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建对象作为默认值返回。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Optional&lt;Author&gt; authorOptional = Optional.ofNullable(getAuthor());</span><br><span class="line">Author author1 = authorOptional.orElseGet(() -&gt; <span class="keyword">new</span> Author());</span><br></pre></td></tr></table></figure></li>
</ul>
<ul>
<li><p>orElseThrow</p>
<p>获取数据，如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建异常抛出。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Optional&lt;Author&gt; authorOptional = Optional.ofNullable(getAuthor());</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    Author author = authorOptional.orElseThrow((Supplier&lt;Throwable&gt;) () -&gt; <span class="keyword">new</span> RuntimeException(<span class="string">&quot;author为空&quot;</span>));</span><br><span class="line">    System.out.println(author.getName());</span><br><span class="line">&#125; <span class="keyword">catch</span> (Throwable throwable) &#123;</span><br><span class="line">    throwable.printStackTrace();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h4 id="4-2-5-过滤"><a href="#4-2-5-过滤" class="headerlink" title="4.2.5 过滤"></a>4.2.5 过滤</h4><p>​    我们可以使用filter方法对数据进行过滤。如果原本是有数据的，但是不符合判断，也会变成一个无数据的Optional对象。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Optional&lt;Author&gt; authorOptional = Optional.ofNullable(getAuthor());</span><br><span class="line">authorOptional.filter(author -&gt; author.getAge()&gt;<span class="number">100</span>).ifPresent(author -&gt; System.out.println(author.getName()));</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h4 id="4-2-6-判断"><a href="#4-2-6-判断" class="headerlink" title="4.2.6 判断"></a>4.2.6 判断</h4><p>​    我们可以使用isPresent方法进行是否存在数据的判断。如果为空返回值为false,如果不为空，返回值为true。但是这种方式并不能体现Optional的好处，<strong>更推荐使用ifPresent方法</strong>。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Optional&lt;Author&gt; authorOptional = Optional.ofNullable(getAuthor());</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (authorOptional.isPresent()) &#123;</span><br><span class="line">    System.out.println(authorOptional.get().getName());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="4-2-7-数据转换"><a href="#4-2-7-数据转换" class="headerlink" title="4.2.7 数据转换"></a>4.2.7 数据转换</h4><p>​    Optional还提供了map可以让我们的对数据进行转换，并且转换得到的数据也还是被Optional包装好的，保证了我们的使用安全。</p>
<p>例如我们想获取作家的书籍集合。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">testMap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Optional&lt;Author&gt; authorOptional = getAuthorOptional();</span><br><span class="line">    Optional&lt;List&lt;Book&gt;&gt; optionalBooks = authorOptional.map(author -&gt; author.getBooks());</span><br><span class="line">    optionalBooks.ifPresent(books -&gt; System.out.println(books));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="5-函数式接口"><a href="#5-函数式接口" class="headerlink" title="5. 函数式接口"></a>5. 函数式接口</h2><h3 id="5-1-概述"><a href="#5-1-概述" class="headerlink" title="5.1 概述"></a>5.1 概述</h3><p>​    <strong>只有一个抽象方法</strong>的接口我们称之为函数接口。</p>
<p>​    JDK的函数式接口都加上了**@FunctionalInterface** 注解进行标识。但是无论是否加上该注解只要接口中只有一个抽象方法，都是函数式接口。</p>
<h3 id="5-2-常见函数式接口"><a href="#5-2-常见函数式接口" class="headerlink" title="5.2 常见函数式接口"></a>5.2 常见函数式接口</h3><ul>
<li><p>​    Consumer 消费接口</p>
<p>根据其中抽象方法的参数列表和返回值类型知道，我们可以在方法中对传入的参数进行消费。</p>
<p><img src="/2022/11/23/java8%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/image-20211028145622163-16354041894551.png" alt="image-20211028145622163"></p>
</li>
<li><p>​    Function 计算转换接口</p>
<p>根据其中抽象方法的参数列表和返回值类型知道，我们可以在方法中对传入的参数计算或转换，把结果返回</p>
<p><img src="/2022/11/23/java8%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/image-20211028145707862-16354042291112.png" alt="image-20211028145707862"></p>
</li>
<li><p>​    Predicate 判断接口</p>
<p>根据其中抽象方法的参数列表和返回值类型知道，我们可以在方法中对传入的参数条件判断，返回判断结果</p>
<p><img src="/2022/11/23/java8%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/image-20211028145818743-16354043004393.png" alt="image-20211028145818743"></p>
</li>
<li><p>​    Supplier 生产型接口</p>
<p>根据其中抽象方法的参数列表和返回值类型知道，我们可以在方法中创建对象，把创建好的对象返回</p>
</li>
</ul>
<p><img src="/2022/11/23/java8%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/image-20211028145843368-16354043246954.png" alt="image-20211028145843368"></p>
<h3 id="5-3-常用的默认方法"><a href="#5-3-常用的默认方法" class="headerlink" title="5.3 常用的默认方法"></a>5.3 常用的默认方法</h3><ul>
<li><p>and</p>
<p>我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&amp;&amp;来拼接两个判断条件</p>
<p>例如：</p>
<p>打印作家中年龄大于17并且姓名的长度大于1的作家。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">Stream&lt;Author&gt; authorStream = authors.stream();</span><br><span class="line">authorStream.filter(<span class="keyword">new</span> Predicate&lt;Author&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">test</span><span class="params">(Author author)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> author.getAge()&gt;<span class="number">17</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;.and(<span class="keyword">new</span> Predicate&lt;Author&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">test</span><span class="params">(Author author)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> author.getName().length()&gt;<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)).forEach(author -&gt; System.out.println(author));</span><br></pre></td></tr></table></figure></li>
<li><p>or </p>
<p>我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件。</p>
<p>例如：</p>
<p>打印作家中年龄大于17或者姓名的长度小于2的作家。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        打印作家中年龄大于17或者姓名的长度小于2的作家。</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        authors.stream()</span><br><span class="line">                .filter(<span class="keyword">new</span> Predicate&lt;Author&gt;() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">test</span><span class="params">(Author author)</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">return</span> author.getAge()&gt;<span class="number">17</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;.or(<span class="keyword">new</span> Predicate&lt;Author&gt;() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">test</span><span class="params">(Author author)</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">return</span> author.getName().length()&lt;<span class="number">2</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;)).forEach(author -&gt; System.out.println(author.getName()));</span><br></pre></td></tr></table></figure></li>
<li><p>negate</p>
<p>Predicate接口中的方法。negate方法相当于是在判断添加前面加了个! 表示取反</p>
<p>例如：</p>
<p>打印作家中年龄不大于17的作家。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//        打印作家中年龄不大于17的作家。</span></span><br><span class="line">        List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">        authors.stream()</span><br><span class="line">                .filter(<span class="keyword">new</span> Predicate&lt;Author&gt;() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">test</span><span class="params">(Author author)</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">return</span> author.getAge()&gt;<span class="number">17</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;.negate()).forEach(author -&gt; System.out.println(author.getAge()));</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="6-方法引用"><a href="#6-方法引用" class="headerlink" title="6. 方法引用"></a>6. 方法引用</h2><p>​    我们在使用lambda时，如果方法体中只有一个方法的调用的话（包括构造方法）,我们可以用方法引用进一步简化代码。</p>
<h3 id="6-1-推荐用法"><a href="#6-1-推荐用法" class="headerlink" title="6.1 推荐用法"></a>6.1 推荐用法</h3><p>​    我们在使用lambda时不需要考虑什么时候用方法引用，用哪种方法引用，方法引用的格式是什么。我们只需要在写完lambda方法发现方法体只有一行代码，并且是方法的调用时使用快捷键尝试是否能够转换成方法引用即可。</p>
<p>​    当我们方法引用使用的多了慢慢的也可以直接写出方法引用。</p>
<h3 id="6-2-基本格式"><a href="#6-2-基本格式" class="headerlink" title="6.2 基本格式"></a>6.2 基本格式</h3><p>​    类名或者对象名::方法名</p>
<h3 id="6-3-语法详解-了解"><a href="#6-3-语法详解-了解" class="headerlink" title="6.3 语法详解(了解)"></a>6.3 语法详解(了解)</h3><h4 id="6-3-1-引用类的静态方法"><a href="#6-3-1-引用类的静态方法" class="headerlink" title="6.3.1 引用类的静态方法"></a>6.3.1 引用类的静态方法</h4><p>​    其实就是引用类的静态方法</p>
<h5 id="格式"><a href="#格式" class="headerlink" title="格式"></a>格式</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">类名::方法名</span><br></pre></td></tr></table></figure>



<h5 id="使用前提"><a href="#使用前提" class="headerlink" title="使用前提"></a>使用前提</h5><p>​    如果我们在重写方法的时候，方法体中<strong>只有一行代码</strong>，并且这行代码是<strong>调用了某个类的静态方法</strong>，并且我们把要重写的<strong>抽象方法中所有的参数都按照顺序传入了这个静态方法中</strong>，这个时候我们就可以引用类的静态方法。</p>
<p>​    </p>
<p>例如：</p>
<p>如下代码就可以用方法引用进行简化</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line">Stream&lt;Author&gt; authorStream = authors.stream();</span><br><span class="line"></span><br><span class="line">authorStream.map(author -&gt; author.getAge())</span><br><span class="line">        .map(age-&gt;String.valueOf(age));</span><br></pre></td></tr></table></figure>

<p>注意，如果我们所重写的方法是没有参数的，调用的方法也是没有参数的也相当于符合以上规则。</p>
<p>优化后如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line">Stream&lt;Author&gt; authorStream = authors.stream();</span><br><span class="line"></span><br><span class="line">authorStream.map(author -&gt; author.getAge())</span><br><span class="line">        .map(String::valueOf);</span><br></pre></td></tr></table></figure>



<h4 id="6-3-2-引用对象的实例方法"><a href="#6-3-2-引用对象的实例方法" class="headerlink" title="6.3.2 引用对象的实例方法"></a>6.3.2 引用对象的实例方法</h4><h5 id="格式-1"><a href="#格式-1" class="headerlink" title="格式"></a>格式</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">对象名::方法名</span><br></pre></td></tr></table></figure>



<h5 id="使用前提-1"><a href="#使用前提-1" class="headerlink" title="使用前提"></a>使用前提</h5><p>​    如果我们在重写方法的时候，方法体中<strong>只有一行代码</strong>，并且这行代码是<strong>调用了某个对象的成员方法</strong>，并且我们把要重写的<strong>抽象方法中所有的参数都按照顺序传入了这个成员方法中</strong>，这个时候我们就可以引用对象的实例方法</p>
<p>例如：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line">Stream&lt;Author&gt; authorStream = authors.stream();</span><br><span class="line">StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">authorStream.map(author -&gt; author.getName())</span><br><span class="line">        .forEach(name-&gt;sb.append(name));</span><br></pre></td></tr></table></figure>

<p>优化后：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line"></span><br><span class="line">Stream&lt;Author&gt; authorStream = authors.stream();</span><br><span class="line">StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">authorStream.map(author -&gt; author.getName())</span><br><span class="line">        .forEach(sb::append);</span><br></pre></td></tr></table></figure>







<h4 id="6-3-4-引用类的实例方法"><a href="#6-3-4-引用类的实例方法" class="headerlink" title="6.3.4 引用类的实例方法"></a>6.3.4 引用类的实例方法</h4><h5 id="格式-2"><a href="#格式-2" class="headerlink" title="格式"></a>格式</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">类名::方法名</span><br></pre></td></tr></table></figure>



<h5 id="使用前提-2"><a href="#使用前提-2" class="headerlink" title="使用前提"></a>使用前提</h5><p>​    如果我们在重写方法的时候，方法体中<strong>只有一行代码</strong>，并且这行代码是<strong>调用了第一个参数的成员方法</strong>，并且我们把要<strong>重写的抽象方法中剩余的所有的参数都按照顺序传入了这个成员方法中</strong>，这个时候我们就可以引用类的实例方法。</p>
<p>例如：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="class"><span class="keyword">interface</span> <span class="title">UseString</span></span>&#123;</span><br><span class="line">       <span class="function">String <span class="title">use</span><span class="params">(String str,<span class="keyword">int</span> start,<span class="keyword">int</span> length)</span></span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">subAuthorName</span><span class="params">(String str, UseString useString)</span></span>&#123;</span><br><span class="line">       <span class="keyword">int</span> start = <span class="number">0</span>;</span><br><span class="line">       <span class="keyword">int</span> length = <span class="number">1</span>;</span><br><span class="line">       <span class="keyword">return</span> useString.use(str,start,length);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">       subAuthorName(<span class="string">&quot;三更草堂&quot;</span>, <span class="keyword">new</span> UseString() &#123;</span><br><span class="line">           <span class="meta">@Override</span></span><br><span class="line">           <span class="function"><span class="keyword">public</span> String <span class="title">use</span><span class="params">(String str, <span class="keyword">int</span> start, <span class="keyword">int</span> length)</span> </span>&#123;</span><br><span class="line">               <span class="keyword">return</span> str.substring(start,length);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>优化后如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    subAuthorName(<span class="string">&quot;三更草堂&quot;</span>, String::substring);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h4 id="6-3-5-构造器引用"><a href="#6-3-5-构造器引用" class="headerlink" title="6.3.5 构造器引用"></a>6.3.5 构造器引用</h4><p>​    如果方法体中的一行代码是构造器的话就可以使用构造器引用。</p>
<h5 id="格式-3"><a href="#格式-3" class="headerlink" title="格式"></a>格式</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">类名::<span class="keyword">new</span></span><br></pre></td></tr></table></figure>



<h5 id="使用前提-3"><a href="#使用前提-3" class="headerlink" title="使用前提"></a>使用前提</h5><p>​    如果我们在重写方法的时候，方法体中<strong>只有一行代码</strong>，并且这行代码是<strong>调用了某个类的构造方法</strong>，并且我们把<strong>要重写的抽象方法中的所有的参数都按照顺序传入了这个构造方法中</strong>，这个时候我们就可以引用构造器。</p>
<p>例如：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">authors.stream()</span><br><span class="line">        .map(author -&gt; author.getName())</span><br><span class="line">        .map(name-&gt;<span class="keyword">new</span> StringBuilder(name))</span><br><span class="line">        .map(sb-&gt;sb.append(<span class="string">&quot;-三更&quot;</span>).toString())</span><br><span class="line">        .forEach(str-&gt; System.out.println(str));</span><br></pre></td></tr></table></figure>

<p>优化后：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">authors.stream()</span><br><span class="line">        .map(author -&gt; author.getName())</span><br><span class="line">        .map(StringBuilder::<span class="keyword">new</span>)</span><br><span class="line">        .map(sb-&gt;sb.append(<span class="string">&quot;-三更&quot;</span>).toString())</span><br><span class="line">        .forEach(str-&gt; System.out.println(str));</span><br></pre></td></tr></table></figure>





<h2 id="7-高级用法"><a href="#7-高级用法" class="headerlink" title="7. 高级用法"></a>7. 高级用法</h2><h3 id="基本数据类型优化"><a href="#基本数据类型优化" class="headerlink" title="基本数据类型优化"></a>基本数据类型优化</h3><p>​    我们之前用到的很多Stream的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。</p>
<p>​    即使我们操作的是整数小数，但是实际用的都是他们的包装类。JDK5中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要消耗时间的。虽然这个时间消耗很下。但是在大量的数据不断的重复装箱拆箱的时候，你就不能无视这个时间损耗了。</p>
<p>​    所以为了让我们能够对这部分的时间消耗进行优化。Stream还提供了很多专门针对基本数据类型的方法。</p>
<p>​    例如：mapToInt,mapToLong,mapToDouble,flatMapToInt,flatMapToDouble等。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test27</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">    authors.stream()</span><br><span class="line">            .map(author -&gt; author.getAge())</span><br><span class="line">            .map(age -&gt; age + <span class="number">10</span>)</span><br><span class="line">            .filter(age-&gt;age&gt;<span class="number">18</span>)</span><br><span class="line">            .map(age-&gt;age+<span class="number">2</span>)</span><br><span class="line">            .forEach(System.out::println);</span><br><span class="line"></span><br><span class="line">    authors.stream()</span><br><span class="line">            .mapToInt(author -&gt; author.getAge())</span><br><span class="line">            .map(age -&gt; age + <span class="number">10</span>)</span><br><span class="line">            .filter(age-&gt;age&gt;<span class="number">18</span>)</span><br><span class="line">            .map(age-&gt;age+<span class="number">2</span>)</span><br><span class="line">            .forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="并行流"><a href="#并行流" class="headerlink" title="并行流"></a>并行流</h3><p>​    当流中有大量元素时，我们可以使用并行流去提高操作的效率。其实并行流就是把任务分配给多个线程去完全。如果我们自己去用代码实现的话其实会非常的复杂，并且要求你对并发编程有足够的理解和认识。而如果我们使用Stream的话，我们只需要修改一个方法的调用就可以使用并行流来帮我们实现，从而提高效率。</p>
<p>​    parallel方法可以把串行流转换成并行流。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test28</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Stream&lt;Integer&gt; stream = Stream.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>);</span><br><span class="line">    Integer sum = stream.parallel()</span><br><span class="line">            .peek(<span class="keyword">new</span> Consumer&lt;Integer&gt;() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">accept</span><span class="params">(Integer num)</span> </span>&#123;</span><br><span class="line">                    System.out.println(num+Thread.currentThread().getName());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">            .filter(num -&gt; num &gt; <span class="number">5</span>)</span><br><span class="line">            .reduce((result, ele) -&gt; result + ele)</span><br><span class="line">            .get();</span><br><span class="line">    System.out.println(sum);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    也可以通过parallelStream直接获取并行流对象。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Author&gt; authors = getAuthors();</span><br><span class="line">authors.parallelStream()</span><br><span class="line">        .map(author -&gt; author.getAge())</span><br><span class="line">        .map(age -&gt; age + <span class="number">10</span>)</span><br><span class="line">        .filter(age-&gt;age&gt;<span class="number">18</span>)</span><br><span class="line">        .map(age-&gt;age+<span class="number">2</span>)</span><br><span class="line">        .forEach(System.out::println);</span><br></pre></td></tr></table></figure>





</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://code-ran.gitee.io">牛牛</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://code-ran.gitee.io/2022/11/23/java8%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/">https://code-ran.gitee.io/2022/11/23/java8%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://code-ran.gitee.io" target="_blank">牛牛&blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/java8/">java8</a></div><div class="post_share"><div class="social-share" data-image="" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/11/23/%E5%B7%A5%E4%BD%9C%E4%B8%AD%E5%B8%B8%E7%94%A8%E7%9A%84lambda%E6%80%BB%E7%BB%93/"><img class="prev-cover" src="" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">工作中常用的lambda总结</div></div></a></div><div class="next-post pull-right"><a href="/2022/11/23/mybatis%E5%AD%A6%E4%B9%A0/"><img class="next-cover" src="" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">MyBatis学习</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/11/23/java8Stream%E8%AF%A6%E8%A7%A3/" title="java8Stream详解"><img class="cover" src="" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-11-23</div><div class="title">java8Stream详解</div></div></a></div><div><a href="/2022/11/23/%E5%B7%A5%E4%BD%9C%E4%B8%AD%E5%B8%B8%E7%94%A8%E7%9A%84lambda%E6%80%BB%E7%BB%93/" title="工作中常用的lambda总结"><img class="cover" src="" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-11-23</div><div class="title">工作中常用的lambda总结</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/ys.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">牛牛</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">52</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">26</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">26</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/code-ran"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">本blog内容仅用于个人学习使用!</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B-Stream%E6%B5%81"><span class="toc-number">1.</span> <span class="toc-text">函数式编程-Stream流</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E6%A6%82%E8%BF%B0"><span class="toc-number">1.1.</span> <span class="toc-text">1. 概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E4%B8%BA%E4%BB%80%E4%B9%88%E5%AD%A6%EF%BC%9F"><span class="toc-number">1.1.1.</span> <span class="toc-text">1.1 为什么学？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3"><span class="toc-number">1.1.2.</span> <span class="toc-text">1.2 函数式编程思想</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-1-%E6%A6%82%E5%BF%B5"><span class="toc-number">1.1.2.1.</span> <span class="toc-text">1.2.1 概念</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-2-%E4%BC%98%E7%82%B9"><span class="toc-number">1.1.2.2.</span> <span class="toc-text">1.2.2 优点</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-Lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-number">1.2.</span> <span class="toc-text">2. Lambda表达式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E6%A6%82%E8%BF%B0"><span class="toc-number">1.2.1.</span> <span class="toc-text">2.1 概述</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-%E6%A0%B8%E5%BF%83%E5%8E%9F%E5%88%99"><span class="toc-number">1.2.2.</span> <span class="toc-text">2.2 核心原则</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E5%9F%BA%E6%9C%AC%E6%A0%BC%E5%BC%8F"><span class="toc-number">1.2.3.</span> <span class="toc-text">2. 3 基本格式</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BE%8B%E4%B8%80"><span class="toc-number">1.2.3.1.</span> <span class="toc-text">例一</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BE%8B%E4%BA%8C"><span class="toc-number">1.2.3.2.</span> <span class="toc-text">例二:</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BE%8B%E4%B8%89%EF%BC%9A"><span class="toc-number">1.2.3.3.</span> <span class="toc-text">例三：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BE%8B%E5%9B%9B%EF%BC%9A"><span class="toc-number">1.2.3.4.</span> <span class="toc-text">例四：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BE%8B%E4%BA%94%EF%BC%9A"><span class="toc-number">1.2.3.5.</span> <span class="toc-text">例五：</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-%E7%9C%81%E7%95%A5%E8%A7%84%E5%88%99"><span class="toc-number">1.2.4.</span> <span class="toc-text">2.4 省略规则</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-Stream%E6%B5%81"><span class="toc-number">1.3.</span> <span class="toc-text">3. Stream流</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-%E6%A6%82%E8%BF%B0"><span class="toc-number">1.3.1.</span> <span class="toc-text">3.1 概述</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-%E6%A1%88%E4%BE%8B%E6%95%B0%E6%8D%AE%E5%87%86%E5%A4%87"><span class="toc-number">1.3.2.</span> <span class="toc-text">3.2 案例数据准备</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8"><span class="toc-number">1.3.3.</span> <span class="toc-text">3.3 快速入门</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3-1-%E9%9C%80%E6%B1%82"><span class="toc-number">1.3.3.1.</span> <span class="toc-text">3.3.1 需求</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3-2-%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.3.3.2.</span> <span class="toc-text">3.3.2 实现</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-4-%E5%B8%B8%E7%94%A8%E6%93%8D%E4%BD%9C"><span class="toc-number">1.3.4.</span> <span class="toc-text">3.4 常用操作</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#3-4-1-%E5%88%9B%E5%BB%BA%E6%B5%81"><span class="toc-number">1.3.4.1.</span> <span class="toc-text">3.4.1 创建流</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-4-2-%E4%B8%AD%E9%97%B4%E6%93%8D%E4%BD%9C"><span class="toc-number">1.3.4.2.</span> <span class="toc-text">3.4.2 中间操作</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#filter"><span class="toc-number">1.3.4.2.1.</span> <span class="toc-text">filter</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#map"><span class="toc-number">1.3.4.2.2.</span> <span class="toc-text">map</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#distinct"><span class="toc-number">1.3.4.2.3.</span> <span class="toc-text">distinct</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#sorted"><span class="toc-number">1.3.4.2.4.</span> <span class="toc-text">sorted</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#limit"><span class="toc-number">1.3.4.2.5.</span> <span class="toc-text">limit</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#skip"><span class="toc-number">1.3.4.2.6.</span> <span class="toc-text">skip</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#flatMap"><span class="toc-number">1.3.4.2.7.</span> <span class="toc-text">flatMap</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-4-3-%E7%BB%88%E7%BB%93%E6%93%8D%E4%BD%9C"><span class="toc-number">1.3.4.3.</span> <span class="toc-text">3.4.3 终结操作</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#forEach"><span class="toc-number">1.3.4.3.1.</span> <span class="toc-text">forEach</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#count"><span class="toc-number">1.3.4.3.2.</span> <span class="toc-text">count</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#max-amp-min"><span class="toc-number">1.3.4.3.3.</span> <span class="toc-text">max&amp;min</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#collect"><span class="toc-number">1.3.4.3.4.</span> <span class="toc-text">collect</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9F%A5%E6%89%BE%E4%B8%8E%E5%8C%B9%E9%85%8D"><span class="toc-number">1.3.4.3.5.</span> <span class="toc-text">查找与匹配</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#anyMatch"><span class="toc-number">1.3.4.3.5.1.</span> <span class="toc-text">anyMatch</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#allMatch"><span class="toc-number">1.3.4.3.5.2.</span> <span class="toc-text">allMatch</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#noneMatch"><span class="toc-number">1.3.4.3.5.3.</span> <span class="toc-text">noneMatch</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#findAny"><span class="toc-number">1.3.4.3.5.4.</span> <span class="toc-text">findAny</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#findFirst"><span class="toc-number">1.3.4.3.5.5.</span> <span class="toc-text">findFirst</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#reduce%E5%BD%92%E5%B9%B6"><span class="toc-number">1.3.4.3.6.</span> <span class="toc-text">reduce归并</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-5-%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9"><span class="toc-number">1.3.5.</span> <span class="toc-text">3.5 注意事项</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-Optional"><span class="toc-number">1.4.</span> <span class="toc-text">4. Optional</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-%E6%A6%82%E8%BF%B0"><span class="toc-number">1.4.1.</span> <span class="toc-text">4.1 概述</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-%E4%BD%BF%E7%94%A8"><span class="toc-number">1.4.2.</span> <span class="toc-text">4.2 使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-1-%E5%88%9B%E5%BB%BA%E5%AF%B9%E8%B1%A1"><span class="toc-number">1.4.2.1.</span> <span class="toc-text">4.2.1 创建对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-2-%E5%AE%89%E5%85%A8%E6%B6%88%E8%B4%B9%E5%80%BC"><span class="toc-number">1.4.2.2.</span> <span class="toc-text">4.2.2 安全消费值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-3-%E8%8E%B7%E5%8F%96%E5%80%BC"><span class="toc-number">1.4.2.3.</span> <span class="toc-text">4.2.3 获取值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-4-%E5%AE%89%E5%85%A8%E8%8E%B7%E5%8F%96%E5%80%BC"><span class="toc-number">1.4.2.4.</span> <span class="toc-text">4.2.4 安全获取值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-5-%E8%BF%87%E6%BB%A4"><span class="toc-number">1.4.2.5.</span> <span class="toc-text">4.2.5 过滤</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-6-%E5%88%A4%E6%96%AD"><span class="toc-number">1.4.2.6.</span> <span class="toc-text">4.2.6 判断</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-7-%E6%95%B0%E6%8D%AE%E8%BD%AC%E6%8D%A2"><span class="toc-number">1.4.2.7.</span> <span class="toc-text">4.2.7 数据转换</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-%E5%87%BD%E6%95%B0%E5%BC%8F%E6%8E%A5%E5%8F%A3"><span class="toc-number">1.5.</span> <span class="toc-text">5. 函数式接口</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-%E6%A6%82%E8%BF%B0"><span class="toc-number">1.5.1.</span> <span class="toc-text">5.1 概述</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-%E5%B8%B8%E8%A7%81%E5%87%BD%E6%95%B0%E5%BC%8F%E6%8E%A5%E5%8F%A3"><span class="toc-number">1.5.2.</span> <span class="toc-text">5.2 常见函数式接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-%E5%B8%B8%E7%94%A8%E7%9A%84%E9%BB%98%E8%AE%A4%E6%96%B9%E6%B3%95"><span class="toc-number">1.5.3.</span> <span class="toc-text">5.3 常用的默认方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-%E6%96%B9%E6%B3%95%E5%BC%95%E7%94%A8"><span class="toc-number">1.6.</span> <span class="toc-text">6. 方法引用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-1-%E6%8E%A8%E8%8D%90%E7%94%A8%E6%B3%95"><span class="toc-number">1.6.1.</span> <span class="toc-text">6.1 推荐用法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2-%E5%9F%BA%E6%9C%AC%E6%A0%BC%E5%BC%8F"><span class="toc-number">1.6.2.</span> <span class="toc-text">6.2 基本格式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-%E8%AF%AD%E6%B3%95%E8%AF%A6%E8%A7%A3-%E4%BA%86%E8%A7%A3"><span class="toc-number">1.6.3.</span> <span class="toc-text">6.3 语法详解(了解)</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#6-3-1-%E5%BC%95%E7%94%A8%E7%B1%BB%E7%9A%84%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95"><span class="toc-number">1.6.3.1.</span> <span class="toc-text">6.3.1 引用类的静态方法</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%A0%BC%E5%BC%8F"><span class="toc-number">1.6.3.1.1.</span> <span class="toc-text">格式</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%89%8D%E6%8F%90"><span class="toc-number">1.6.3.1.2.</span> <span class="toc-text">使用前提</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-3-2-%E5%BC%95%E7%94%A8%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%AE%9E%E4%BE%8B%E6%96%B9%E6%B3%95"><span class="toc-number">1.6.3.2.</span> <span class="toc-text">6.3.2 引用对象的实例方法</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%A0%BC%E5%BC%8F-1"><span class="toc-number">1.6.3.2.1.</span> <span class="toc-text">格式</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%89%8D%E6%8F%90-1"><span class="toc-number">1.6.3.2.2.</span> <span class="toc-text">使用前提</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-3-4-%E5%BC%95%E7%94%A8%E7%B1%BB%E7%9A%84%E5%AE%9E%E4%BE%8B%E6%96%B9%E6%B3%95"><span class="toc-number">1.6.3.3.</span> <span class="toc-text">6.3.4 引用类的实例方法</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%A0%BC%E5%BC%8F-2"><span class="toc-number">1.6.3.3.1.</span> <span class="toc-text">格式</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%89%8D%E6%8F%90-2"><span class="toc-number">1.6.3.3.2.</span> <span class="toc-text">使用前提</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-3-5-%E6%9E%84%E9%80%A0%E5%99%A8%E5%BC%95%E7%94%A8"><span class="toc-number">1.6.3.4.</span> <span class="toc-text">6.3.5 构造器引用</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%A0%BC%E5%BC%8F-3"><span class="toc-number">1.6.3.4.1.</span> <span class="toc-text">格式</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%89%8D%E6%8F%90-3"><span class="toc-number">1.6.3.4.2.</span> <span class="toc-text">使用前提</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-%E9%AB%98%E7%BA%A7%E7%94%A8%E6%B3%95"><span class="toc-number">1.7.</span> <span class="toc-text">7. 高级用法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E4%BC%98%E5%8C%96"><span class="toc-number">1.7.1.</span> <span class="toc-text">基本数据类型优化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B9%B6%E8%A1%8C%E6%B5%81"><span class="toc-number">1.7.2.</span> <span class="toc-text">并行流</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/04/30/springboot%E6%B3%A8%E8%A7%A3%E7%9B%B8%E5%85%B3/" title="springboot注解相关">springboot注解相关</a><time datetime="2024-04-30T03:20:37.000Z" title="发表于 2024-04-30 11:20:37">2024-04-30</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/04/30/CommandLineRunner%E5%92%8CApplicationRunner%E7%94%A8%E6%B3%95%E4%B8%8E%E5%8C%BA%E5%88%AB/" title="CommandLineRunner和ApplicationRunner用法与区别">CommandLineRunner和ApplicationRunner用法与区别</a><time datetime="2024-04-30T02:42:21.000Z" title="发表于 2024-04-30 10:42:21">2024-04-30</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/12/08/%E5%A5%BD%E6%96%87%E6%94%B6%E8%97%8F/" title="好文收藏">好文收藏</a><time datetime="2023-12-08T08:40:13.000Z" title="发表于 2023-12-08 16:40:13">2023-12-08</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/12/08/springboot%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8B%E8%BD%BD/" title="springboot文件上传下载">springboot文件上传下载</a><time datetime="2023-12-08T03:30:54.000Z" title="发表于 2023-12-08 11:30:54">2023-12-08</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/12/05/linux%E4%BD%BF%E7%94%A8curl%E5%91%BD%E4%BB%A4%E5%8F%91%E9%80%81%E8%AF%B7%E6%B1%82/" title="linux使用curl命令发送请求">linux使用curl命令发送请求</a><time datetime="2023-12-05T05:56:19.000Z" title="发表于 2023-12-05 13:56:19">2023-12-05</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 - 2024 By 牛牛</div><div class="footer_custom_text">Hi, Welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">簡</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>